package com.eras.shoes.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.google.zxing.client.android.BuildConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static final String CRASH_DIR_NAME = "CrashLogs"; // 目录名
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    public static void init(Context context) {
        CrashHandler handler = new CrashHandler(context);
        Thread.setDefaultUncaughtExceptionHandler(handler);
    }

    private CrashHandler(Context context) {
        mContext = context.getApplicationContext();
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        saveCrashLog(ex);  // 保存日志
        mDefaultHandler.uncaughtException(thread, ex); // 默认处理崩溃
    }

    private void saveCrashLog(Throwable ex) {
        try {
            // 1. 获取崩溃信息
            String crashLog = getCrashLogText(ex);

            // 2. 获取SD卡根目录路径（需适配Android版本）
            File crashDir = getExternalStorageCrashDir();
            if (crashDir == null) {
                Log.e(TAG, "无法访问SD卡根目录");
                return;
            }

            // 3. 保存文件
            String fileName = "crash_" + System.currentTimeMillis() + ".log";
            File crashFile = new File(crashDir, fileName);
            FileOutputStream fos = new FileOutputStream(crashFile);
            fos.write(crashLog.getBytes());
            fos.close();

            Log.d(TAG, "崩溃日志已保存至: " + crashFile.getAbsolutePath());
        } catch (Exception e) {
            Log.e(TAG, "保存崩溃日志失败", e);
        }
    }

    // 获取SD卡根目录下的CrashLogs目录（适配Android版本）
    private File getExternalStorageCrashDir() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 无法直接访问根目录，改用公有目录的Documents子目录
            File dir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), CRASH_DIR_NAME);
            if (!dir.exists()) dir.mkdirs();
            return dir;
        } else {
            // Android 9及以下：直接尝试访问/sdcard/CrashLogs
            File dir = new File(Environment.getExternalStorageDirectory(), CRASH_DIR_NAME);
            if (!dir.exists()) dir.mkdirs();
            return dir;
        }
    }

    // 生成完整的崩溃日志文本
    private String getCrashLogText(Throwable ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        return String.format(
                "Time: %s\nDevice: %s %s\nAndroid SDK: %d\nApp Version: %s\n\n%s",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()),
                Build.BRAND, Build.MODEL, Build.VERSION.SDK_INT, BuildConfig.VERSION_NAME,
                sw.toString()
        );
    }
}
